package crawler.baoshijie;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zql.entity.AgencyEntity;

import crawler.leikesasi.FengTianQiCheCrawler;
import dao.AgencyDao;
import util.HttpConnectionGet;
import util.Location;
import util.MybatisTool;
import util.TianYanCha;

@SuppressWarnings("unused")
public class BaoShiJie {

	private JSONArray provinces;

	BaoShiJie() {
		provinces = getCity();
	}

	/**
	 * 
	 * @return 中国所有城市
	 * @throws IOException
	 */
	JSONArray getCity() {
		try {
			InputStream is = BaoShiJie.class.getResourceAsStream("/cities");
			BufferedReader bf = new BufferedReader(new InputStreamReader(is));
			String line = null;
			StringBuffer total = new StringBuffer();
			while ((line = bf.readLine()) != null) {
				total = total.append(line);
			}
			JSONObject json = JSONObject.parseObject(total.toString());
			JSONArray provinces = json.getJSONArray("provinces");
			return provinces;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	List<AgencyEntity> getAgency() {
		List<AgencyEntity> list = new ArrayList<AgencyEntity>();
		for (int i = 0; i < provinces.size(); i++) {
			JSONObject province = provinces.getJSONObject(i);
			String proName = province.getString("provinceName");
			JSONArray citys = province.getJSONArray("citys");
			for (int j = 0; j < citys.size(); j++) {
				String cityName = citys.getJSONObject(j).getString("citysName");
				// 获取经纬度
				String[] lngAndLat = Location.getLocation(cityName);
				if ("/".equals(lngAndLat[0])) {
					continue;
				}
				String getDealer = "https://www.porsche.com/all/dealer2/GetLocationsWebService.asmx/GetLocationsInStateSpecialJS?market=china&siteId=china&language=zh&state=&_locationType=Search.LocationTypes.Dealer&searchMode=proximity&searchKey="
						+ lngAndLat[1] + "|" + lngAndLat[0] + "&address=" + cityName
						+ "&maxproximity=&maxnumtries=&maxresults=";
				String dealerXML = HttpConnectionGet.getJson(getDealer);
				// 利用dom4j解析xml字符串
				Document doc = null;
				try {
					doc = DocumentHelper.parseText(dealerXML);
				} catch (DocumentException e) {
					e.printStackTrace();
				}
				Element root = doc.getRootElement();
				String result = root.element("Result").elementText("Code");
				// 查询此城市无经销商,跳过此城市
				if (!"OK".equals(result)) {
					continue;
				}
				List<Element> locations = root.element("ListofLocations").elements("Location");
				for (Element location : locations) {
					String name = location.elementText("Name");
					Element addressData = location.element("AddressData");
					String city = addressData.elementText("City");
					// 查询城市和返回城市不统一,跳过此城市
					if (!cityName.equals(city)) {
						continue;
					}
					String address = addressData.elementText("Street");
					String saleTell = addressData.elementText("Phone");

					String[] lngAndLat1 = Location.getLocation(address);
					String lng = lngAndLat1[0];
					String lat = lngAndLat1[1];
					List<String> shareholder = TianYanCha.getShareholder(name);
					String sControllingShareholder = shareholder.get(0);
					String sOtherShareholders = shareholder.get(1);

					// 开始存入agency实体类
					AgencyEntity agency = new AgencyEntity();
					agency.setdCloseDate(null);
					agency.setdOpeningDate(null);
					agency.setdUpdateTime(new Timestamp(System.currentTimeMillis()));
					agency.setnBrandID(-1);
					agency.setsBrand("保时捷");
					agency.setnDealerIDWeb(-1);
					agency.setnManufacturerID(-1);
					agency.setsManufacturer("保时捷");
					agency.setnState(1);
					agency.setsAddress(address);
					agency.setsCity(cityName);
					agency.setsCustomerServiceCall("");
					agency.setsDealerName(name);
					agency.setsDealerType("");
					agency.setsProvince(proName);
					agency.setsSaleCall(saleTell);

					agency.setsLongitude(lng);
					agency.setsLatitude(lat);
					agency.setsControllingShareholder(sControllingShareholder);
					agency.setsOtherShareholders(sOtherShareholders);
					System.out.println(agency);
					list.add(agency);
				}

			}
		}
		return list;
	}

	public static void main(String[] args) throws IOException, DocumentException {
		BaoShiJie crawler = new BaoShiJie();
		System.out.println("爬虫开始...");
		List<AgencyEntity> agencys = crawler.getAgency();
		System.out.println("抓取完毕,正在存库");
		for (AgencyEntity agency : agencys) {
			MybatisTool.save(agency);
		}
		MybatisTool.close();
		System.out.println("请查看数据库");
	}
}
